<template>
    <div class="view">
        <Header title="填写"/>
        <van-cell class="vanCell-class">
            <div class="content">
                <span style="color:#0095FF;font-size:16px;line-height:24px;font-weight:600;">{{ title }}</span><br/>
                <span style="color:#9a9b9d;font-size:8px">{{description}}</span>
            </div>
            <hr>
            <van-form @submit="onSubmit" ref="formFormRef">
                <div v-for="(item,index) in allQuestions" :key="item.id" style="margin-top:10vw">
                    <div style="display: flex;">
                        <span style="color: red;margin:1vw">*</span>
                        <div style="flex-grow: 1;">
                            <span style="color:#262626">{{index + 1}}.&nbsp;{{ item.question }}</span>
                            <span style="color:#808080">【{{ questionType[item.type] }}】</span>
                        </div>
                    </div>
                    <van-cell-group inset>
                        <!-- 多选框  max多选的最大限制   -->
                        <van-checkbox-group v-if="item.type === 1" v-model="currentQuestionnaire.answers[item.id].answer">
                            <van-checkbox :name="i" shape="square" v-for="(it,i) in JSON.parse(item.content).choices" :key="i"
                                          style="margin-top:10px;">
                                <span style="color:#808080">{{it}}</span>
                            </van-checkbox>
                        </van-checkbox-group>
                        <!-- 单选框-->
                        <van-radio-group v-if="item.type === 2" v-model="currentQuestionnaire.answers[item.id].answer">
                            <van-radio v-for="(it, i) in JSON.parse(item.content).choices" :key="i" :value="i" :name="i" style="margin-top:10px;">
                                <span style="color:#808080">{{it}}</span>
                            </van-radio>
                        </van-radio-group>
                        <!-- 进度条  max滑动条最大值限制-->
                        <van-cell v-if="item.type === 3" v-for="(itslider,i) in JSON.parse(item.content)" :key="i">
                            <span style="color:#808080">{{itslider.tag}}</span>
                            <var-row justify="space-between" style="display:flex">
                                <var-col :span="14">
                                    <van-slider  style="margin-top:20px;margin-left:10px" v-model.number="currentQuestionnaire.answers[item.id].answer[i]" :max="itslider.max"  @change="onChange" />
                                </var-col>
                                <var-col :span="8">
                                    <van-field  style="margin-top:8px;" v-model.number="currentQuestionnaire.answers[item.id].answer[i]" type="number" label="" class="van-field__control"/>
                                </var-col>
                            </var-row>
                        </van-cell>
                        <!-- 输入框-->
                        <van-cell-group v-if="item.type === 4" style="margin-top:20px">
                            <van-field
                                    v-model="currentQuestionnaire.answers[item.id].answer"
                                    rows="1"
                                    autosize
                                    class="van-field__control"
                                    type="textarea"
                                    placeholder="请输入"
                            />
                        </van-cell-group>
                        <!-- 院系下拉框-->
                        <var-select
                                placeholder="请选择"
                                v-if="item.type === 5"
                                v-model="currentQuestionnaire.answers[item.id].answer"
                        >
                            <var-option v-for="item in options" :key="item.value" :value="item.value" :label="item.text" style="color:#808080;width:92vw"/>
                        </var-select>
                        <!-- 专业下拉框-->
                        <var-select
                                v-if="item.type === 6"
                                placeholder="请选择"
                                v-model="currentQuestionnaire.answers[item.id].answer[0]"
                        >
                            <var-option v-for="item in options" :key="item.value" :value="item.value" :label="item.text" style="color:#808080;width:92vw"/>
                        </var-select>
                        <!-- 下拉框 这里还需要改下拉框样式-->
                        <var-select
                            placeholder="请选择"
                            v-if="item.type === 7"
                            v-model="currentQuestionnaire.answers[item.id].answer"
                        >
                            <var-option v-for="item in othersOptions" :key="item.value" :value="item.value" :label="item.text" style="color:#808080;width:92vw"/>
                        </var-select>
                    </van-cell-group>
                    <var-chip :round="false" v-show="item.isShow" :key="item.id" class="chip-class">
                        <template #left>
                            <var-icon name="close-circle" color="red"/>
                        </template>
                        <label>请选择选项</label>
                    </var-chip>
                </div>
                <van-button type="primary" style="margin-top:15%;height:35px" block native-type="submit">提交</van-button>
            </van-form>
        </van-cell>
        <van-empty v-if="allQuestions === null" image="search" description="无答卷记录！"/>
    </div>
</template>

<script setup>
import {Dialog, Toast} from "vant";
import {getMyQuestionnaireDefine, submitQuestionnaire} from "/@/api/new_module/questionNaire";
import {initQuestionAnswer, questionTypes} from "/@/utils/questionNaire";
import {useRouter} from "vue-router";
import 'vant/es/dialog/style'; //局部引入样式

const router = useRouter();
const route = useRoute()
const currentQuestionnaire = ref({})
const id = ref('')
const type = ref('')
const ids = ref('')
const title = ref('')
const description = ref("")
const allQuestions = ref([])
const question = ref("")
const answersYY = ref({})
/** 学院字典*/
const options = ref([
    { text: '湖北民族大学', value: '00' },
    { text: '文学与传媒学院', value: '01' },
    { text: '数学与统计学院', value: '02' },
    { text: '智能科学与工程学院', value: '03' },
    { text: '化学与环境工程学院', value: '04' },
    { text: '医学部', value: '05' },
    { text: '经济与管理学院', value: '06' },
    { text: '生物与食品工程学院', value: '07' },
    { text: '外国语学院', value: '08' },
    { text: '体育学院', value: '09' },
    { text: '美术与设计学院', value: '10' },
    { text: '法学院', value: '11' },
    { text: '马克思主义学院', value: '12' },
    { text: '临床医学院', value: '13' },
    { text: '音乐舞蹈学院', value: '14' },
    { text: '教师教育学院', value: '15' },
    { text: '民族学与社会学学院', value: '16' },
    { text: '林学园艺学院', value: '17' },
    { text: '中医药学院', value: '18' },
    { text: '国际学院', value: '19' },
    { text: '新材料与机电工程学院', value: '21' },
    { text: '创新创业教育学院', value: '22' },
    { text: '创新创业教育学院', value: '22' },
    { text: '学生工作部处', value: '35' },
    { text: '招生就业处', value: '42' },
]);
/** 对题目下拉框字典处理*/
const othersOptions = computed(() => {
    let contents = [];
    allQuestions.value.forEach(item => {
        if(item.type === 7){
            contents.push(item.content);
        }
    });
    let choices = [];
    contents.forEach(content => {
        let parsedContent = JSON.parse(content);
        choices = choices.concat(parsedContent.choices);
    });

    return choices.map((choice, index) => ({
        text: choice,
        value: index,
    }));
});

/** 获取要填写的问卷以及答案*/
const initData = async ()=>{
    id.value = route.query.id
    if (!id.value) return;
    let res =  await getMyQuestionnaireDefine(id.value)
    let rawValue = res.response._rawValue
    currentQuestionnaire.value = rawValue.data
    title.value = currentQuestionnaire.value.title
    description.value = currentQuestionnaire.value.description
    allQuestions.value = currentQuestionnaire.value.questions
    allQuestions.value.forEach(item => {
        ids.value = item.id
        type.value = item.type
        question.value = item.question
    })
    initAnswers();
}
/** 题型匹配*/
const questionType = computed(() => {
    const result = {};
    allQuestions.value.forEach(item => {
        result[item.type] = questionTypes[item.type] || '未知类型';
    });
    return result;
})
/** 进度条拉动提示*/
const onChange = (value) => Toast('当前值：' + value);
/** 初始化题目答案*/
const initAnswers = () => {
    if (allQuestions.value) {
        const state = ref('')
        allQuestions.value.forEach((v, index) => {
            if (currentQuestionnaire.value.answers) {
                state.value = 0
                if (typeof currentQuestionnaire.value.answers === 'string') {
                    //解析问卷的答案
                    currentQuestionnaire.value.answers = JSON.parse(currentQuestionnaire.value.answers)
                }
            } else {
                    state.value = 1
                    answersYY.value[v.id] = initQuestionAnswer(v)
            }
        })
        if(state.value == 1) {
            currentQuestionnaire.value.answers = {}
            allQuestions.value.forEach(item => {
                currentQuestionnaire.value.answers[item.id] =  answersYY.value[item.id]
            })
        }

    }
    else {
        //根据索引下标做
        allQuestions.value.forEach(((v, index) => {
            //没有填写答案的给一个
            v.id = index;
            currentQuestionnaire.value.answers[index] = currentQuestionnaire.value.answers[v.id] = initQuestionAnswer(v)
        }))
    }
};
/** 更新状态展示未填写题目的状态 */
const updateItemShowStatus =()=> {
    allQuestions.value.forEach((item, index) => {
        item.isShow = false; // 初始化为 false
        let type = item.type
        if((type === 1 || type === 6) &&  currentQuestionnaire.value.answers[item.id].answer.length === 0) {
            item.isShow = true;
        }else if((type === 2 || type === 7) && currentQuestionnaire.value.answers[item.id].answer === -1){
            item.isShow = true;
        }else if((type === 4 || type === 5) && currentQuestionnaire.value.answers[item.id].answer === ""){
            item.isShow = true;
        }else if(type === 3){
            const answerArray = Object.values(currentQuestionnaire.value.answers[item.id].answer);
            if(answerArray.some(answer => answer === 0)){
                item.isShow = true;
            }
        }
    })
}
/** 提交按钮*/
const onSubmit = async ()=>{
    // 在提交之前对答案进行转换
    const answers = {};
    for (const key in currentQuestionnaire.value.answers) {
        if (Object.hasOwnProperty.call(currentQuestionnaire.value.answers, key)) {
            const answer = currentQuestionnaire.value.answers[key];
            if (typeof answer === 'string') {
                answers[key] = parseInt(answer); // 将字符串转换为整数
            } else {
                answers[key] = answer;
            }
        }
    }
    const datas = {
        id: Number(route.query.id),
        answers: JSON.stringify(answers)
    }
    updateItemShowStatus();
    //监听提交后未填写的是否填了
    watch(() => currentQuestionnaire.value.answers,
        (newVal, oldVal) => {
            // 新的答案值更新显示状态
            updateItemShowStatus();
        },
        { deep: true }
    );
    // 检查是否所有的 item.isShow 都为 false ==>表示都填了
    const allItemsHidden = allQuestions.value.every(item => !item.isShow);
    //已答完
    if(allItemsHidden){
        await Dialog.confirm({
            message:
                '是否确认提交答卷？',
        })
            .then(() => {
                submitQuestionnaire(datas).then(res=>{
                    Toast(`${res.response._value.msg}`);
                })
                router.push('/questionNaire')

            })
            .catch(() => {
            });
    }else{ //未答完
        Toast('请完成答卷再提交！')
    }
}

watchEffect(() => {
    initData()
})
onMounted(() =>{
    initData()
})
</script>

<style lang="scss" scoped>
.vanCell-class {
  margin: 3vw 4vw 3vw 4vw;
  width: 92vw;
  display:flex;
  justify-content:center;
  background-color:#fff;
    .content{
    text-align: center;
  }
  hr{
    color:#9a9b9d;
    margin-top:5vw;
  }
  .van-dropdown__control{
    width:92vw;
    margin-left:4vw;
  }
  .van-field__control {
    border: 1px solid #ccc;
    border-radius: 4px;
    text-align: center;
    line-height:4vh;
    color:#808080;
  }
    .chip-class{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 92vw;
        margin-top: 2vw;
        background-color: #FFD8E4;
    }
}
</style>
